import {objectCompare }  from '../../../assets/js/objectCompare.js'
import {compareObject } from '../../../assets/js/util.js'
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.addUserForm.addUserSurePassword !== '') {
          this.$refs.addUserForm.validateField('addUserSurePassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.addUserForm.addUserPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    return {
      // 用户名为空
      userVal: '',
      //请求后台路径
      SRC:'',
      /*当前页显示数量*/
      pageSize: 10,
      /*每页显示的数量*/
      pageSizes: [10, 20, 50, 100],
      /*dataTotal表数量*/
      dataTotal: 0,
      /*分页器*/
      currentPage: 1,
      // roleShow 角色工程tree
      roleShow: true,
      // 穿梭匡选角色数据显示
      roleChooseShow: false,
      // 穿梭匡数据
      roleData: [],
      //穿梭匡已选数据
      roleValue: [],
      // 穿梭匡搜索
      filterMethod(query, item) {
        return item.name.indexOf(query) > -1;
      },
      // 保存userID
      userId : 0,
      // 保存工程ID
      projectId: 0,
      // 获取到的每个用户每个工程的数据
      projectRoleData : [[],[]],
      // 全部删除按钮显示隐藏
      deleteBtn: false,
      // 添加用户信息显示
      addUserShow: false,
      // 修改用户信息
      userShow: false,
      /*initWidth 的宽*/
      initWidth:'100%',
      // deleteBtn 显示
      deleteBtn: false,
      // 表格数据
      tableData: [],
      tableDataAll: [],
      // 工程数据
      projectData: [],
      // 存放表格每一行选择的数据
      multipleSelection: [],
      //用户列表添加弹框数据
      addUserForm: {
        addUserName: '',
        addUserDepartment: '',
        addUserPassword: '',
        addUserSurePassword: '',
        addUserDescription:'',
        addUserIsAdmin: false
      },
      //添加用户数据验证
      addRules: {
        addUserName: [
          { required: true,  message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        addUserDepartment: [
          { required: true, message: '请输入所属部门', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        addUserPassword: [
          { required: true, validator: validatePass, trigger: 'blur' },
          { min: 8, max: 32, message: '长度在 8 到 32 个字符', trigger: 'blur' }
        ],
        addUserSurePassword: [
          { required: true, validator: validatePass2, trigger: 'blur' },
          { min: 8, max: 32, message: '长度在 8 到 32 个字符', trigger: 'blur' }
        ]
      }, 
      //用户列表数据
      revampForm: {
        id : 0,
        username : '',
        department : '',
        password : '',
        isAdmin : false,
        description : '',
      },
      // 用户列框数据验证
      rules: {
        username: [
          { required: true,  message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请输入用户描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ]
      }, 
    }
  },
  methods: {
    // 通用 成功 与 失败
    successFun(data) {
      this.$message({
        message: data,
        type: 'success'
      });
    },
    errorFun(data) {
      this.$message.error(data);
    },
    // 控制每页的数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.tableControl();
    },
    // 页数
    handleCurrentChange(val) {
      this.currentPage = val;
      this.tableControl();
    },
    tableControl() {
      this.dataTotal = this.tableDataAll.length;
      this.tableData = this.tableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
    },
    // 用户显示
    addUserShowFun() {
      //重置form数据 
      for(let i in this.addUserForm){
        this.addUserForm[i] = '';
      }
      this.addUserShow = true;
    },
    // 修改用户
    userEdit(index, row){
      this.revampForm = row;
      this.revampForm.password = '';
      this.userShow = true;
    },
    // 编辑权限
    handleEdit(index, row) {
      this.userId = row.id;
      this.getProjectList(row.id);
    },
    // 删除用户
    handleDelete(index, row) {
      this.$http.post(this.SRC+"user/delete.do",{userId:row.id},{emulateJSON:true}).then(
        function(res){
          if(res.body["code"] === 0 ){
            this.successFun('删除成功！')
            this.getUsersData();
          }else{
            this.errorFun('删除失败'+res.body["msg"]+"！");
          }
        }
      )
    },
    // 全部删除
    handleDeleteAll() {
      this.tableData=[];
    },
    handleSelectionChange(val) {
      if(val.length === this.tableData.length  &&  val.length>0){
        this.deleteBtn = true;
      }else{
        this.deleteBtn = false;
      }
    },
     /*设置初始值*/
    _init(){
      window.addEventListener('resize', function() {
        /*修改表格的宽度*/
            this.initWidth = document.body.clientWidth-220+"px";
        }.bind(this))
    },  
    // 添加用户提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let d = this.addUserForm;
          if( d.addUserIsAdmin == ""){
            d.addUserIsAdmin =false;
          }
          let obj = {
            username : d.addUserName,
            department : d.addUserDepartment,
            password : d.addUserPassword,
            isAdmin : d.addUserIsAdmin,
            description : d.addUserDescription
          };
          this.$http.post(this.SRC+"user/add.do",obj,{emulateJSON:true}).then(function(res){
              if(res.body['code'] === 0){
                this.successFun("添加数据成功！");
                this.getUsersData();
                this.getProjectRoleData(this.userId);
              }else{
                this.errorFun("添加数据失败"+res.body['msg']+"！")
              }
            }
          )
          this.tableDataAll = objectCompare(this.tableData,"id")// 排序
          this.tableControl();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 添加用户重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 修改用户信息
    userRevamp(formName) {
      this.$refs[formName].validate((valid) => {
        var d = this.revampForm;
        if (valid) {
          this.$http.post(`${this.SRC}user/modify.do?id=${d.id}&username=${d.username}&password=${d.password}&department=${d.department}&isAdmin=${d.isAdmin}&description=${d.description}`).then(
            function(res){
              if(res.body['code'] === 0){
                this.successFun("修改数据成功！");
                this.getUsersData();
              }else{
                this.errorFun("修改数据失败"+res.body['msg']+"！")
              }
            }
          )
          this.tableDataAll = objectCompare(this.tableData,"id")// 排序
          this.tableControl();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    revampReset(formName) {
      this.$refs[formName].resetFields();
    },
    // 配置角色
    revamp(store, data){
      this.projectId = data.id;
      this.roleValue = [];
      this.getProjectRoleData();
      this.roleChooseShow = true;
    },
    // 链接跳转
    href(stroe,data){
      window.open(data.url,"_blank")
    }, 
    // 渲染
    renderContent(h, { node, data, store }) {
      var rows = [];
      if(data['roles'] !== undefined && data['roles'].length>0){
        var getRoles = data['roles'];
      }else{
        var getRoles = [];
      }
      for (var i=0; i < getRoles.length; i++) {
          rows.push(<span class="el-tag" style="margin-left: 5px;">角色：{getRoles[i]['name']}</span>);
      };
      /*return (
        <span>
          <span>
            <span class="el-tag el-tag--gray">{data.projectName}</span>
          </span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">工程标识：{data.id}</span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">工程SRC：{data.projectUrl}</span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">工程描述：{data.description}</span>
          <span style="float: right; margin-right: 20px">
            <el-button size="mini" type="warning" on-click={ () => this.revamp(store, data) }>选择角色</el-button>
          </span>
          <span style="float: right; margin-right: 20px">{rows}</span>
        </span>);*/
      return (
        <span>
          <span>
            <span class="el-tag el-tag--gray">{data.projectName}</span>
          </span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">工程标识：{data.id}</span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">工程描述：{data.description}</span>
          <span style="float: right; margin-right: 20px">
            <el-button size="mini" type="warning" on-click={ () => this.revamp(store, data) }>选择角色</el-button>
          </span>
          <span style="float: right; margin-right: 20px">{rows}</span>
        </span>);
    },
    //查看选择的角色
    handleChange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys)
    },
    // 选择角色提交
    roleChooseSubmit() {
      var obj = {
        userId : this.userId,
        projectId : this.projectId,
        roleId : this.roleValue
      }
      this.$http.post(this.SRC+'user_project_role/modify.do',obj).then(
        function(res){
          if(res.body["code"] === 0){
            this.successFun(res.body["msg"]);
            this.roleShow = true;
            this.getProjectList(obj.userId);
          }else{
            this.errorFun(res.body['msg']);
          }
        }
      )
    },
    // 选择的角色重置
    roleChooseReset() {
      this.roleValue = [];
    },
    // 获取用户列表数据
    getUsersData() {
      this.$http.post(this.SRC+'user/list.do').then(
        function(res){
          if(res.body["code"] === 0){
            this.tableDataAll = res.body["msg"];
            this.tableControl();
          }else{
            this.errorFun(res.body['msg']);
          }
        }
      )
    },
    // 获取工程名称数据
    getProjectData() {
      this.$http.post(this.SRC+'project/list.do').then(
        function(res){
          if(res.body["code"] === 0){
            this.projectData = res.body["msg"];
          }else{
            this.errorFun(res.body['msg']);
          }
        }
      )
    },
    // 获取角色列表
    getRolesData() {
      this.$http.post(this.SRC+'role/list.do').then(
        function(res){
          if(res.body["code"] === 0){
            this.roleData = res.body["msg"];
          }else{
            this.errorFun(res.body['msg']);
          }
        }
      )
    },
    // 获取一个用户的一个工程下的所有角色
    getProjectRoleData() {
      var that = this;
      var p = new Promise(
        function(resolve,reject){
          that.$http.post(that.SRC+'user_project_role/roles.do',{userId:that.userId,projectId:that.projectId},{emulateJSON:true}).then(
            function(res){
              if(res.body["code"] === 0){
                resolve(res.body["msg"])
              }else{
                that.errorFun(res.body['msg']);
              }
            }
          )
        }
      );
      p.then(function(value){
        that.projectRoleData[0] = [];
        that.projectRoleData[1] = [];
        for(var i=0; i<value.length; i++){
          that.projectRoleData[0].push(value[i][0]);
          that.projectRoleData[1].push(value[i][1]);
        }
        that.projectData['roles'] = that.projectRoleData[1];
        that.roleValue = that.projectRoleData[0];
      })
    },
    // 获取工程list列表
    getProjectList(id) {
      var that = this;
      var p = new Promise(function(resolve,reject){
        that.$http.post(that.SRC+'user_project_role/projects.do',{userId:id},{emulateJSON:true}).then(
          function(res){
            if(res.body["code"] === 0 ){
              resolve(res.body["msg"]);
            }else{
              console.log(res.body["msg"]+"！");
            }
          }
        )
      })
      p.then(function(value){
        var d = that.projectData;
        for(var i = 0; i<d.length; i++){
          d[i]["roles"] = undefined;
          for(var j in value){
            if(d[i]["id"] === parseInt(j)){
              d[i]["roles"] = value[j];
            }
          }
        }
        that.roleShow = false;
      })
    },
    // 表格排序
    sortChange(column) {
        if (column.prop === null) {
            return;
        } else if (column.order === 'descending') {
            this.tableDataAll.sort(compareObject(column.prop, false));
        } else { //正序
            this.tableDataAll.sort(compareObject(column.prop, true));
        }
        this.tableControl();
    },
  },
  computed: {
    // 用户过滤
    newUSers: function() {
      var that = this;
      return that.tableDataAll.filter(function(item) {
        return item.username.toLowerCase().indexOf(that.userVal.toLowerCase()) !== -1;
      })
    }
  },
  mounted() {
    this.SRC = this.$store.getters.src;
    this._init();
    this.getUsersData();
    this.getProjectData();
    this.getRolesData();
    this.tableDataAll = objectCompare(this.tableData,"id")// 排序
    this.tableControl();
    this.projectData = objectCompare(this.projectData,"id")// 排序
  },

}